﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using App.Core.Extensions;
using App.Data;
using System.IO;

public partial class Pages_Private_EventChange : BasePage
{
    private int _ID = 0;
    private bool _IsEditMode = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        BindPageInfo();
        if (!IsPostBack)
        {            
            BindEventInfo();
            ShowSuccessMessage();
        }
    }
    /// <summary>
    /// Bindis the Page Initialization Variables
    /// </summary>
    protected void BindPageInfo()
    {
        _ID = WebUtil.GetQueryStringInInt(AppConstants.QueryString.ID);

        if (_ID > 0)
        {
            _IsEditMode = true;
            h4Heading.InnerHtml = "Edit Event";
        }
        Page.Title = WebUtil.GetPageTitle(h4Heading.InnerHtml);
    }
   
    /// <summary>
    /// Binds Event Info Requested through Query Strings
    /// </summary>
    protected void BindEventInfo()
    {
        if (_IsEditMode)
        {
            BtcHousingEntities context = new BtcHousingEntities();
            Event entity = context.Events.FirstOrDefault(P => P.ID == _ID);//dao.GetByID(_ID);
            if (entity == null)
                ShowErrorMessage();
            else
            {
                if (!entity.ThumbImageFile.IsNullOrEmpty())
                {
                    divEventPreviewContainer.InnerHtml = String.Format("<img class='EventImage' src='{0}/{1}' alt='' title='' />", AppConstants.EVENT_FILES, entity.ThumbImageFile);
                    divEventPreviewContainer.Visible = true;
                }

                txtTitle.Text = entity.Title;
                txtDescription.Text = entity.Description;
                txtEventDate.Text = entity.EventDate;
                txtVenue.Text = entity.Venue;
            }
        }
    }
    protected void ShowSuccessMessage()
    {
        if (String.Compare(WebUtil.GetQueryStringInString(AppConstants.QueryString.SUCCESS_MESSAGE), "True", true) == 0)
            WebUtil.ShowMessageBox(divMessage, "Event Saved Successfully.", false);
    }
    /// <summary>
    /// Shows a Message in the UI and Hides the Data Editing Controls
    /// </summary>
    protected void ShowErrorMessage()
    {
        pnlFormContainer.Visible = false;
        WebUtil.ShowMessageBox(divMessage, "Requested Event was not found.", true);
    }
    protected void SaveEvent()
    {
        BtcHousingEntities context = new BtcHousingEntities();
        Event entity = null;

        if (_IsEditMode)
            entity = context.Events.FirstOrDefault(P => P.ID == _ID); //dao.GetByID(_ID);        
        else
        {
            entity = new Event();
            entity.Created = DateTime.Now;
            context.AddToEvents(entity);
        }

        entity.Title = txtTitle.Text.Trim();
        entity.Description = txtDescription.Text.Trim();
        entity.EventDate = txtEventDate.Text.Trim();
        entity.Venue = txtVenue.Text.Trim();
        entity.Modified = DateTime.Now;
        entity.ModifiedBy = SessionCache.CurrentUser.ID;
        context.SaveChanges();

        if (fuImageFile.HasFile)
        {
            String filePath = Server.MapPath(AppConstants.EVENT_FILES);
            if(!Directory.Exists(filePath))
                Directory.CreateDirectory(filePath);

            ///Delete Existing Image at first
            if (_IsEditMode && !entity.ImageFile.IsNullOrEmpty())
            {
                String file = Path.Combine(filePath, entity.ImageFile);
                if (File.Exists(file))
                    File.Delete(file);
            }

            if (!entity.ThumbImageFile.IsNullOrEmpty())
            {
                String fileThumb = Path.Combine(filePath, entity.ThumbImageFile);
                if (File.Exists(fileThumb))
                    File.Delete(fileThumb);
            }


            String outputFileName = Path.Combine(filePath, String.Format("{0}_{1}_Thumb{2}", entity.ID, Path.GetFileNameWithoutExtension(fuImageFile.PostedFile.FileName), Path.GetExtension(fuImageFile.PostedFile.FileName)));
            String inputFileName = Path.Combine(filePath, String.Format("{0}_{1}", entity.ID, Path.GetFileName(fuImageFile.PostedFile.FileName)));
            fuImageFile.SaveAs(inputFileName);
            WebUtil.GenerateThumbnail(inputFileName, outputFileName, ConfigReader.EventThumbWidth, false);

            ///Set File Names
            entity.ImageFile = Path.GetFileName(inputFileName);
            entity.ThumbImageFile = Path.GetFileName(outputFileName);

            context.SaveChanges();
        }
        _ID = entity.ID;
        WebUtil.ShowMessageBox(divMessage, "Event Saved Successfully.", false);        
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            SaveEvent();
            Response.Redirect(String.Format("{0}?{1}={2}&{3}=True", AppConstants.Pages.EVENT_CHANGE, AppConstants.QueryString.ID, _ID, AppConstants.QueryString.SUCCESS_MESSAGE)) ;
            return;
        }
    }
    protected void btnList_Click(object sender, EventArgs e)
    {
        Response.Redirect(AppConstants.Pages.EVENT_LIST);
        return;
    }

    protected void cvImageFile_OnServerValidate(object sender, ServerValidateEventArgs e)
    {
        if (fuImageFile.HasFile)
        {
            if (WebUtil.IsValidImageFile(fuImageFile.PostedFile) )
                e.IsValid = true;
            else
                e.IsValid = false;
        }
        //if (_IsEditMode && !fuFile.HasFile)
        //    e.IsValid = true;
        //elseup
        //    e.IsValid = false;
    }
}